package com.administration;

import static org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4;
import com.carpark.ejb.DAO.SitesDAO;
import com.carpark.ejb.DAO.SitesDAOImpl;
import com.carpark.ejb.Model.SitesModel;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Piotr
 */
@ManagedBean
@ViewScoped
public class WelcomeEditor implements Serializable {
    private static final String PAGE_CHANGED = "Zmieniono stronę.";
    private static final String TITLE = "Home"; // title to home
    private final SitesDAO sitesDao = new SitesDAOImpl();
    private String htmlCode = null;
    
    @PostConstruct
    public void fetchSiteFromDataBase() {
        htmlCode = readTitleSite();
  
      

    
    }
    public void saveTitleSite() {
        SitesModel siteToAdd = new SitesModel(htmlCode, TITLE);
        Logger.getLogger(WelcomeEditor.class.getName()).log(Level.SEVERE, "[CarPark] Created new welcome site: {0}", htmlCode);
        sitesDao.addSite(siteToAdd);
        createErrorMessage(PAGE_CHANGED);
    }

    public String readTitleSite() {
        List<SitesModel> sites = sitesDao.getSiteByType(TITLE);
        int last = sites.size() -1;
        if(last < 0) {
            return "";
        }
        return unescapeHtml4(sites.get(last).getHtml());
    }
    
    private void createErrorMessage(String info) {
        FacesMessage msg = new FacesMessage();
        msg.setSeverity(FacesMessage.SEVERITY_INFO);
        msg.setSummary(info);
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
    
    public String getHtmlCode() {
        return htmlCode;
    }

    public void setHtmlCode(String htmlCode) {
        this.htmlCode = htmlCode;
    }
    
}
